<template>
  <n-scrollbar x-scrollable style="max-height: 100vh">
    <CommonPage show-footer>
      <div>
        <n-form ref="form"
                :model="searchCondition"
                label-placement="left"
                label-align="right"
                label-width="80px"
                :show-require-mark="false">
          <div>
            <div class="grid md:flex md:flex-wrap md:gap-x-1">
              <n-form-item>
                  <label style="width: 100px;">物流订单编号：</label>
                  <n-input style="width: 160px;" v-model:value="searchCondition.id" placeholder="输入物流订单编号" clearable/>
              </n-form-item>
              <n-form-item style="margin-left: 10px">
                  <label style="width: 100px;">客户订单编号：</label>
                  <n-input style="width: 160px;" v-model:value="searchCondition.customerOrderId" placeholder="输入客户订单编号" clearable/>
              </n-form-item>
              <n-form-item style="margin-left: 10px">
                  <label style="width: 90px;">物流商名称：</label>
                  <n-input style="width: 160px;" v-model:value="searchCondition.name" placeholder="输入物流商名称" clearable/>
              </n-form-item>
              <n-form-item style="margin-left: 10px">
                <label style="width: 70px;">运输状态：</label>
                <n-select v-model:value="searchCondition.status"
                          placeholder="筛选状态"
                          :options="statusOptions"
                          filterable
                ></n-select>
              </n-form-item>
              <n-form-item>
                  <n-button type="primary" style="margin-left: 10px" @click="searchByCondition">筛选</n-button>
              </n-form-item>
              <n-form-item>
                <n-button style=" margin-left: 10px"
                          type="error"
                          @click="deleteSelectLogisticsOrder">
                  批量删除
                </n-button>
              </n-form-item>
              <n-form-item>
                <n-button type="primary" style="margin-left: 10px" @click="showForm=true">添加物流订单</n-button>
              </n-form-item>
              <n-form-item style="margin-left: 10px">
                <n-button @click="exportListInfo"
                          type="primary">
                  导出
                </n-button>
              </n-form-item>
            </div>
          </div>
        </n-form>
      </div>
      <AddLogisticsOrderForm
          :statusOptions="filteredStatusOptions"
          :logisticsChannels="logisticsChannels"
          :logistics="logistics"
          @update-page="searchByCondition"
          :show="showForm"
          :onClose="handleClose"
      />
      <UpdateLogisticsOrderForm
          :statusOptions="filteredStatusOptions"
          :logisticsChannels="logisticsChannels"
          :logistics="logistics"
          @update-page="searchByCondition"
          :show1="showForm1"
          :onClose="handleClose"
          :attribute="currentAttribute"
      />
      <LogisticsOrderStatusForm
          :statusOptions="filteredStatusOptions"
          :logisticsChannels="logisticsChannels"
          :logistics="logistics"
          @update-page="searchByCondition"
          :show1="showForm2"
          :onClose="handleClose"
          :attribute="currentAttribute"
      />
      <n-data-table
          remote
          :single-line="false"
          ref="table"
          :columns="columns"
          :data="logisticsOrderList"
          :loading="loading"
          :pagination="paginationReactive"
          :row-key="rowKey"
          :header-cell-style="{ textAlign: 'center' }"
          :cell-style="{ textAlign: 'center' }"
          @update:checked-row-keys="handleCheck"
      />
    </CommonPage>
  </n-scrollbar>
</template>

<script setup>
import {h, onMounted, reactive, ref} from 'vue'
import api from '@/api/admin';
import LogisticsOrderActions from "@/views/admin/logistics-statics/components/logistics-order-actions.vue";
import {useUserStore} from '@/store';
import {useRouter} from 'vue-router';
import AddLogisticsOrderForm from './components/logistics-order-add.vue';
import UpdateLogisticsOrderForm from './components/logistics-order-edit.vue'
import LogisticsOrderStatusForm from './components/logistics-order-status.vue'
import {NTag} from "naive-ui";

const showForm = ref(false);
const showForm1 = ref(false);
const showForm2 = ref(false);
const userStore = useUserStore()
const router = useRouter()
const rules = ref(null)
const courseInfoRef = ref(null)
const loading = ref(true)
const courseList = ref([])
const checkedRowKeysRef = ref([]);
const currentAttribute = ref(null); // 当前编辑的属性
let total = 0
const handleCheck = (rowKeys) => {
  checkedRowKeysRef.value = rowKeys;
}
const handleClose = () => {
  showForm.value = false;
  showForm1.value = false;
  showForm2.value = false;
};

const logistics = ref([])
const queryLogisticsList = async () => {
  loading.value = true
  try {
    const res = await api.findAllLogisticsProvider()
    if (res.code === 200) {
      res.data.map((item) => {
        logistics.value.push({
          label: item.name,
          value: item.name
        })
      })
    } else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取物流商信息失败！")
  } finally {
    loading.value = false
  }
}

const paginationReactive = reactive({
  page: 1,
  pageSize: 50,
  showSizePicker: true,
  pageSizes: [50, 100, 150],
  itemCount: 0,
  prefix: () => {
    return '查询出 ' + total + '条记录';
  },
  onChange: (page) => {
    paginationReactive.page = page;
    queryByPage()
  },
  onUpdatePageSize: (pageSize) => {
    paginationReactive.pageSize = pageSize;
    paginationReactive.page = 1;
    queryByPage()
  }
});
const courseInfoValue = ref({
  name: '',
  pageNum: paginationReactive.page,
  pageSize: paginationReactive.pageSize,
  customer_id: '',
});
const logisticsOptions = ref({})
const statusOptions = ref([
  {
    label: "全部",
    value: "全部"
  },
  {
    label: '未发货',
    value: '未发货',
  },
  {
    label: '运输中',
    value: '运输中',
  },
  {
    label: '已送达',
    value: '已送达',
  }
])
const logisticsChannels = ref([
  {
    label: '海派',
    value: '海派',
  },
  {
    label: '空派',
    value: '空派',
  },
  {
    label: '快递',
    value: '快递',
  },
  {
    label: '铁运',
    value: '铁运',
  }
])

// 过滤掉 '全部' 选项
const filteredStatusOptions = computed(() => statusOptions.value.filter(statusOption => statusOption.value !== "全部"));

const onAdd = () => {
  router.push({name: 'AdminCourseAdd'})
}
const columns = [
  {
    type: 'selection',
    fixed: 'left',
  },
  {
    key: 'colId',
    title: '序号',
    width: 60,
  },
  {
      key: 'id',
      title: '物流订单编号',
      width: '60',
  },
  {
      key: 'customerOrderId',
      title: '客户订单编号',
      width: '60',
  },
  {
      key: 'logisticsChannels',
      title: '配送方式',
      width: '50',
  },
  {
      key: 'price',
      title: '物流费用',
      width: '50',
  },
  {
      key: 'name',
      title: '物流商',
      width: '50',
  },
  {
      key: 'phone',
      title: '联系电话',
      width: '60',
  },
  {
    key: 'startTime',
    title: '开始时间',
    width: '70',
  },
  {
    key: 'endTime',
    title: '结束时间',
    width: '70',
  },
	{
		key: 'status',
		title: '运输状态',
		width: '50',
    render(row) {
      if (row.status === "未发货") {
        return h(
            NTag,
            {
              type: 'info',
              bordered: false,
              style: {cursor: 'pointer'},
              onClick: () => handleStatusClick(row)
            },
            {
              default: () => '未发货'
            }
        );
      } else if (row.status === "运输中") {
        return h(
            NTag,
            {
              type: 'info',
              bordered: false,
              style: {cursor: 'pointer'},
              onClick: () => handleStatusClick(row)
            },
            {
              default: () => '运输中'
            }
        );
      } else if (row.status === "已送达") {
        return h(
            NTag,
            {
              type: 'success',
              bordered: false,
              style: {cursor: 'pointer'},
            },
            {
              default: () => '已送达'
            }
        );
      }
    }
	},
  {
      key: 'actions',
      title: '操作',
      width: '60',
      render(row) {
          return h(
	          LogisticsOrderActions,
              {
                  onClickEdit: () => onEditLogisticsProviderOrder(row),
                  onClickDelete: () => onDeleteLogisticsProviderOrders(row),
              }
          );
      }
  },
]
const handleStatusClick = async (LogisticsProviderOrder) => {
  currentAttribute.value = LogisticsProviderOrder; // 设置当前编辑的属性
  showForm2.value = true; // 显示编辑窗口
}
const deleteSelectLogisticsOrder = () => {
  if (checkedRowKeysRef.value.length <= 0) {
    $message.error("当前并未选择物流订单！")
    return
  }
  $dialog.confirm({
    title: '警告',
    content: '您确定删除当前所选物流订单？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const ids = checkedRowKeysRef.value.join(",")
      console.log(ids)
      loading.value = true
      try {
        const res = await api.deleteLogisticsProviderOrders({ params: { ids } })
        if (res.code === 200) {
          $message.success("删除所选物流订单成功！")
          // await queryByPage()
          await searchByCondition()
        } else {
          $message.error(res.message)
        }
      } catch (err) {
        $message.error("删除所选物流订单失败！")
      } finally {
        loading.value = false
      }
    },
  })
}
const onEditLogisticsProviderOrder = async (logisticsProviderOrder) => {
  currentAttribute.value = logisticsProviderOrder; // 设置当前编辑的属性
  showForm1.value = true; // 显示编辑窗口
}
const logisticsOrderList=ref([])
const searchCondition = ref({
  id: "",
  name: "",
  status: "全部",
  customerOrderId: ""
})
const searchByCondition = async () => {
	loading.value = true
	try {
		paginationReactive.page = 1;
		const res = await api.findPageLogisticsProviderOrder({
			params: {
				...searchCondition.value,
				pageNum: paginationReactive.page,
				pageSize: paginationReactive.pageSize,
			}
		})
		if(res.code === 200) {
			total = res.data.total
			paginationReactive.itemCount = total
			logisticsOrderList.value = res.data.records.map((item, i) => {
        return {
          ...item,
          colId: i + 1
        }
      })
		}
		else {
			$message.error(res.message)
		}
	} catch (err) {
		$message.error("查询物流订单失败！")
	}finally{
		loading.value = false
	}
}
const exportListInfo = async () => {
  const res = await api.exportLogisticsOrderList({
    id: searchCondition.value.id,
    name: searchCondition.value.name,
    status: searchCondition.value.status,
    customerOrderId: searchCondition.value.customerOrderId
  });
  const contentDisposition = res.headers["content-disposition"]
  let original_fileName = ""
  if(contentDisposition) {
    const uri = res.headers["content-disposition"].split("=")[1]
    original_fileName = window.decodeURI(uri)
  }
  const blob = new Blob([res.data], {type: "application/vnd.ms-excel"});
  if(window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob, original_fileName);
  } else{
    const fileName = original_fileName;
    const elink = document.createElement('a')
    document.body.appendChild(elink)
    elink.download= fileName;
    elink.style.display ="none"
    elink.href  = window.URL.createObjectURL(blob)
    elink.click()
    window.URL.revokeObjectURL(elink.href)
    document.body.removeChild(elink)
  }
}
const queryByPage = async ()=>{
  loading.value = true
  try {
    const res = await api.findPageLogisticsProviderOrder({
        params:{
          pageNum: paginationReactive.page,
          pageSize: paginationReactive.pageSize,
        }
      })
    if(res.code === 200) {
	    total = res.data.total
	    paginationReactive.itemCount = total
	    logisticsOrderList.value = res.data.records.map((item, i) => {
        return {
          ...item,
          colId: i + 1
        }
      })
      $message.success("获取物流商成功！")
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取物流商失败！")
  }finally{
    loading.value = false
  }
}
const sub = async ()=>{
    courseInfoRef.value?.validate(async (errors) => {
        await queryByPage(1)
    })
}

const onDeleteLogisticsProviderOrders = (row) => {
  $dialog.warning({
    title: '警告',
    content: '您确定删除此物流订单？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      loading.value = true
      try {
        const res = await api.deleteLogisticsProviderOrder({ id: row.id})
        if (res.code === 200) {
          $message.success("删除物流订单成功！")
          await queryByPage()
        }
        else {
          $message.error(res.message)
        }
      } catch (err) {
        $message.error("删除物流订单失败！")
      } finally {
        loading.value = false
      }
    }
  })
}

const onEditCourses=async (courses)=>{
    const {id} = courses
    await router.push({name: 'AdminCourseEdit', params: {chId: id}})
}
const rowKey = (rowData) => {
    return rowData.id
}
onMounted(()=>{
  queryByPage(paginationReactive.page)
  queryLogisticsList()
})
</script>
<style scoped>
:deep(.n-data-table-th__title),
:deep(.n-data-table-td) {
    text-align: center;

}
:deep(.n-select) {
    width: 120px !important;
}

:deep(.two-line-description) {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2; /* 控制显示的行数 */
    overflow: hidden;
}
</style>
